<template>
  <div class="fixed top-0 bottom-0 left-0 right-0 flex">
    <div class="flex items-center flex-1 ">
      <div class="bg-[url('../assets/meeting.png')] bg-contain bg-no-repeat w-[50%] h-[50%] ml-28">
      </div>
    </div>
    <div class="flex flex-col justify-center pl-10 pr-4 bg-gray-100 w-96">
      <h2 class="mb-8 text-xl font-semibold text-center text-gray-600 ">CStar人事管理系统</h2>
      <el-form ref="formRef" style="max-width: 600px" :model="accountForm" label-width="auto" :rules="rules">
        <el-form-item prop="loginname" label="用户名">
          <el-input v-model="accountForm.loginname" />
        </el-form-item>
        <el-form-item prop="password" label="密&nbsp&nbsp&nbsp&nbsp码">
          <el-input v-model="accountForm.password" type="password" />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="accountForm.remember" label="记住密码" size="large" />
        </el-form-item>
      </el-form>
      <div class="mx-auto">
        <el-button type="primary" @click="loginByAccount(formRef)">登陆</el-button>
        <el-button @click="faceVisible = true">刷脸登陆</el-button>
      </div>
    </div>
  </div>

  <el-dialog v-model="faceVisible" title="人脸识别" width="500">
    <video ref="video" autoplay></video>
    <canvas ref="canvas" style="display:none;"></canvas>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="faceVisible = false">Cancel</el-button>
        <el-button type="primary" @click="loginByFace">
          Confirm
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { onBeforeMount, reactive, ref, watch } from 'vue'
import { ElMessage, ElNotification, type FormInstance } from 'element-plus'
import { ApiPost } from '@/utils/Axios';
import { useInfoStore } from '../stores/useInfoStore';
const info = useInfoStore();
const formRef = ref<FormInstance>()
const faceVisible = ref(false)
const video = ref(null);
const canvas = ref(null);
const faceReisterResult = ref(false)

onBeforeMount(() => {
  window.localStorage.removeItem("token")
})

watch(faceVisible, (newVal, oldVal) => {
  if (newVal) {
    navigator.mediaDevices.getUserMedia({ video: true })
      .then(stream => {
        video.value.srcObject = stream;
        video.value.play();
      })
      .catch(error => {
        console.error('Error accessing video stream', error);
      });
  } else {
    if (video.value.srcObject) {
      const stream = video.value.srcObject;
      const tracks = stream.getTracks();
      tracks.forEach(track => {
        track.stop();
      });
      video.value.srcObject = null;
    }
  }
})
const accountForm = reactive({
  loginname: "",
  password: "",
  remember: false
})

const loginByAccount = (formEl: FormInstance | undefined) => {
  formEl.validate(vail => {
    if (vail) {
      ApiPost("/login", {
        loginname: accountForm.loginname,
        password: accountForm.password,
      }).then(res => {
        if (res.code === 200) {
          ElNotification({
            title: "登陆成功",
            type: 'success',
            showClose: false,
            duration: 1500,
            onClose: () => {
              info.$patch = { ...res.data }
              window.localStorage.setItem("userinfo", JSON.stringify(res.data))
              window.localStorage.setItem("token", res.data.token)
              window.location.replace("/")
            }
          })
        } else {
          ElNotification({
            title: res.msg,
            type: 'error',
            showClose: false,
          })
        }
      }).catch(err => {
        console.log(err)
      })
    }
  })
}


const validateLoginname = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('账号不能为空'))
  } else {
    callback()
  }
}

const validatePassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('密码不能为空'))
  } else {
    callback()
  }
}

const sendImageData = (imageData) => {
  // 这里使用fetch API发送数据到后端
  // 假设后端服务的URL是 http://your-backend.com/face-recognize
  ApiPost("/faceLogin", {
    base64ImageStr: imageData,
  }).then((res) => {
    console.log(res, "人脸登陆",res)
    faceReisterResult.value = true
    if (res.code === 200) {
      faceVisible.value = false
      ElMessage({
        message: '登陆成功',
        type: 'success',
        duration: 2000,
        onClose: () => {
          info.$patch = {...res.data }
          window.localStorage.setItem("userinfo", JSON.stringify(res.data))
          window.localStorage.setItem("token", res.data.token)
          window.location.replace("/")
        }
      })
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const loginByFace = () => {
  faceReisterResult.value = false
  if (!faceReisterResult.value) {
    canvas.value.width = video.value.videoWidth;
    canvas.value.height = video.value.videoHeight;
    const ctx = canvas.value.getContext('2d');
    ctx.drawImage(video.value, 0, 0, canvas.value.width, canvas.value.height);
    const imageData = canvas.value.toDataURL('image/jpeg');
    sendImageData(imageData)
  }

}
const rules = reactive({
  loginname: [{ validator: validateLoginname, trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }],
})


</script>

<style></style>